package cn.zh.stan.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;

import cn.zh.stan.BaseUrl;
import cn.zh.stan.ITem.CAItem;
import cn.zh.stan.ITem.FiItem;
import cn.zh.stan.ITem.OrItem;
import cn.zh.stan.ITem.ReItem;
import cn.zh.stan.ITem.SItem;
import cn.zh.stan.MyApplication;
import cn.zh.stan.R;
import cn.zh.stan.adapter.FAdapter;
import cn.zh.stan.util.MyListView;
import cn.zh.stan.util.ToastUtil;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FilOrder extends BaseActivity {

    ImageView fil_back;
    LinearLayout readress,sendformat;
    ArrayList<CAItem> datas=null;
    TextView totaey,tomoney;
    double tomon=0;
    TextView sytxt;
    MyListView flist;
    FAdapter fAdapter;
    TextView suborder;
    TextView fname,fphon,fadres;
    ReItem reItem=null;//地址
    SItem sItem=null;//配送方式
    MyApplication mapp;
    String uid;
    EditText mark;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fil_order);
        datas= (ArrayList<CAItem>) getIntent().getSerializableExtra("cd");
        mapp= (MyApplication) getApplication();
        uid=mapp.getSp().getString("uid","");
        getAdrss();
        gettrade();
        inivi();
        }


    public void inivi(){
        fil_back= (ImageView) findViewById(R.id.fil_back);
        readress= (LinearLayout) findViewById(R.id.readress);
        sendformat= (LinearLayout) findViewById(R.id.sendformat);
        totaey=(TextView)findViewById(R.id.totaey);
        sytxt=(TextView)findViewById(R.id.sytxt);
        tomoney=(TextView)findViewById(R.id.tomoney);
        suborder=(TextView)findViewById(R.id.suborder);
        fname=(TextView)findViewById(R.id.fname);
        fphon=(TextView)findViewById(R.id.fphon);
        fadres=(TextView)findViewById(R.id.fadres);
        mark= (EditText) findViewById(R.id.mark);
        for (int j=0;j<datas.size();j++){
            tomon=tomon+datas.get(j).getNum()*datas.get(j).getPrice_Detail();
         }
        totaey.setText(tomon+"");
        tomoney.setText(tomon+"");
        flist= (MyListView) findViewById(R.id.flist);
        fAdapter=new FAdapter(FilOrder.this,datas);
        flist.setAdapter(fAdapter);
        fil_back.setOnClickListener(this);
        readress.setOnClickListener(this);
        sendformat.setOnClickListener(this);
        suborder.setOnClickListener(this);
        }




    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id=view.getId();
        switch (id){
            case R.id.fil_back:
                finish();
                break;
            case R.id.readress:
                Intent intent=new Intent(FilOrder.this,ReAdrass.class);
                startActivityForResult(intent,0);
                break;

            case R.id.sendformat:
                Intent intent2=new Intent(FilOrder.this,SendFormat.class);
                startActivityForResult(intent2,1);
                break;
            case R.id.suborder:
                //提交订单
                getcreat();
                break;
                }
            }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null==data){
            return;
        }

        switch (requestCode){
            case 0:
                reItem = (ReItem) data.getSerializableExtra("AI");
                fname.setText("收货人:"+reItem.getPersonName());
                fphon.setText(reItem.getMoblie());
                fadres.setText("收货地址:"+reItem.getProvinceName()+reItem.getCityName()+reItem.getCountyName()+reItem.getAddress()+reItem.getCompanyName());
                break;
            case 1:
                sItem = (SItem) data.getSerializableExtra("oj");
                sytxt.setText(sItem.getName());
                break;
             }
          }


    public void getAdrss(){
        OkHttpUtils.get(BaseUrl.adress_list)
                .params("userId",uid)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        //获取用户地址列表
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray ja=js.getJSONArray("Res");
                                       if (ja.length()==0){
                                           return;
                                       }
                                    JSONObject jo=ja.getJSONObject(0);
                                    String Id =jo.getString("Id");
                                    String MemberId =jo.getString("MemberId");
                                    String ProvinceId =jo.getString("ProvinceId");
                                    String ProvinceName =jo.getString("ProvinceName");
                                    String CityId =jo.getString("CityId");
                                    String CityName =jo.getString("CityName");
                                    String CountyId =jo.getString("CountyId");
                                    String CountyName =jo.getString("CountyName");
                                    String CompanyName =jo.getString("CompanyName");
                                    String PersonName =jo.getString("PersonName");
                                    String Address =jo.getString("Address");
                                    String Moblie =jo.getString("Moblie");
                                    String IsDefault =jo.getString("IsDefault");
                                    String CreateTime =jo.getString("CreateTime");
                                   reItem=new ReItem(Id,MemberId,ProvinceId,ProvinceName,
                                            CityId,CityName,CountyId,CountyName,CompanyName,PersonName,
                                            Address,Moblie,IsDefault,CreateTime);

                                fname.setText("收货人:"+reItem.getPersonName());
                                fphon.setText(reItem.getMoblie());
                                fadres.setText("收货地址:"+reItem.getProvinceName()+reItem.getCityName()+reItem.getCountyName()+reItem.getAddress()+reItem.getCompanyName());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                  });
                 }


            public void getcreat(){
              ArrayList<FiItem> fiItems=new ArrayList<>();
                if (null==reItem){
                    ToastUtil.showShort(FilOrder.this,"请选择地址");
                    return;
                    }
                  if (null==sItem){
                      ToastUtil.showShort(FilOrder.this,"请选择配送方式");
                      return;
                    }
                   suborder.setEnabled(false);
                   fiItems.clear();
                   for (int i=0;i<datas.size();i++){
                       FiItem fiItem=new FiItem(datas.get(i).getGoodsId(),"0",datas.get(i).getGoodsName(),datas.get(i).getNum()+"",datas.get(i).getPrice_Detail()+"",datas.get(i).getUnit(),"b.jpg");
                       fiItems.add(fiItem);
                        }
                 String marktxt=mark.getText().toString();

                   OrItem orItem=new OrItem();
                   orItem.setUserId(uid);
                   orItem.setAddressId(reItem.getId());
                   orItem.setCustomer_remark(marktxt);
                   orItem.setLogisticId(sItem.getLogisticID());
                   orItem.setPostage_total("0");
                   orItem.setGoods_total(tomon+"");
                   orItem.setGoods(fiItems);
                   Gson  gso=new Gson();
                 String js=gso.toJson(orItem);

                 OkHttpUtils.post(BaseUrl.CreateOrder)
                         .mediaType(MediaType.parse("application/json; charset=utf-8"))
                         .postJson(js)
                         .execute(new StringCallback() {
                             @Override
                             public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                                 System.out.println("----------------->创建订单结果=="+s);
                                 suborder.setEnabled(true);
                                 try {
                                     JSONObject js=new JSONObject(s);
                                     boolean State=js.getBoolean("State");
                                     if (State){
                                        boolean Flag=js.getBoolean("Flag");
                                        if (Flag){
                                            String Res=js.getString("Res");
                                            Intent intent=new Intent(FilOrder.this,ToPay.class);
                                            intent.putExtra("tradeNo",Res);
                                            String str=tomon+"";
                                            intent.putExtra("tomon",str);
                                            startActivity(intent);
                                        }else {
                                         String Msg=js.getString("Msg");
                                         ToastUtil.showLong(FilOrder.this,Msg);
                                        }
                                     }
                                 } catch (JSONException e) {
                                     e.printStackTrace();
                                 }
                             }
                             @Override
                             public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                                 super.onError(isFromCache, call, response, e);
                             }
                         });
                       }




    public void gettrade(){
        OkHttpUtils.get(BaseUrl.trade_get)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        System.out.println("--------->获取配送方式===="+s);
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                boolean Flag=js.getBoolean("Flag");
                                if (Flag){
                                    JSONArray ja=js.getJSONArray("Res");
                                      if (0==ja.length()){
                                          return;
                                        }
                                        JSONObject ji=ja.getJSONObject(0);
                                        String Name=ji.getString("Name");
                                        String LinkMan=ji.getString("LinkMan");
                                        String Tel=ji.getString("Tel");
                                        String bMonthCharge=ji.getString("bMonthCharge");
                                        String BillStyle=ji.getString("BillStyle");
                                        String Remark=ji.getString("Remark");
                                        String OrderPos=ji.getString("OrderPos");
                                        String LogisticID=ji.getString("LogisticID");
                                        String WebSite=ji.getString("WebSite");
                                        String bBlockUp=ji.getString("bBlockUp");
                                        String Balance=ji.getString("Balance");
                                        String bSendStyle=ji.getString("bSendStyle");
                                        String type="0";
                                        SItem sIte=new SItem(Name,LinkMan,Tel,bMonthCharge,BillStyle,Remark,OrderPos,LogisticID,WebSite,bBlockUp,Balance,bSendStyle,type);
                                     if (null==sItem){
                                         sItem=sIte;
                                         sytxt.setText(sItem.getName());
                                     }
                                }else {
                                    String Msg=js.getString("Msg");
                                    ToastUtil.showLong(FilOrder.this,Msg);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                  });
               }


              }
